import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';

/// 像素画编辑器页面
class PixelArtEditorPage extends StatefulWidget {
  const PixelArtEditorPage({super.key});

  @override
  State<PixelArtEditorPage> createState() => _PixelArtEditorPageState();
}

class _PixelArtEditorPageState extends State<PixelArtEditorPage> {
  // 画布相关
  List<DrawingPoint?> drawingPoints = [];
  Color selectedColor = Colors.black;
  double strokeWidth = 5.0;
  
  // 尺寸选项（米）
  final List<double> sizeOptions = [50, 100, 200, 500, 1000];
  double selectedSize = 100.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('创建像素画'),
        backgroundColor: CustomColor.primaryColor,
        foregroundColor: Colors.white,
        actions: [
          TextButton(
            onPressed: _savePixelArt,
            child: const Text(
              '保存',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 工具栏
          _buildToolBar(),
          // 画布
          Expanded(
            child: GestureDetector(
              onPanStart: (details) {
                setState(() {
                  drawingPoints.add(
                    DrawingPoint(
                      details.localPosition,
                      Paint()
                        ..color = selectedColor
                        ..strokeWidth = strokeWidth
                        ..strokeCap = StrokeCap.round,
                    ),
                  );
                });
              },
              onPanUpdate: (details) {
                setState(() {
                  drawingPoints.add(
                    DrawingPoint(
                      details.localPosition,
                      Paint()
                        ..color = selectedColor
                        ..strokeWidth = strokeWidth
                        ..strokeCap = StrokeCap.round,
                    ),
                  );
                });
              },
              onPanEnd: (details) {
                setState(() {
                  drawingPoints.add(null); // 用于分隔不同的笔画
                });
              },
              child: Container(
                color: Colors.white,
                child: CustomPaint(
                  painter: DrawingPainter(drawingPoints),
                  child: Container(),
                ),
              ),
            ),
          ),
          // 底部操作栏
          _buildBottomBar(),
        ],
      ),
    );
  }

  Widget _buildToolBar() {
    return Container(
      padding: const EdgeInsets.all(10),
      color: Colors.grey[200],
      child: Row(
        children: [
          const Text('颜色：'),
          const SizedBox(width: 10),
          ..._buildColorPickers(),
          const Spacer(),
          IconButton(
            icon: const Icon(Icons.delete_outline),
            onPressed: () {
              setState(() {
                drawingPoints.clear();
              });
            },
            tooltip: '清空画布',
          ),
        ],
      ),
    );
  }

  List<Widget> _buildColorPickers() {
    final colors = [
      Colors.black,
      Colors.red,
      Colors.blue,
      Colors.green,
      Colors.yellow,
      Colors.purple,
      Colors.orange,
    ];

    return colors.map((color) {
      return GestureDetector(
        onTap: () {
          setState(() {
            selectedColor = color;
          });
        },
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 5),
          width: 30,
          height: 30,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
            border: Border.all(
              color: selectedColor == color
                  ? CustomColor.primaryColor
                  : Colors.transparent,
              width: 3,
            ),
          ),
        ),
      );
    }).toList();
  }

  Widget _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '像素画大小（在地图上的实际尺寸）',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
          const SizedBox(height: 10),
          Row(
            children: sizeOptions.map((size) {
              return Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      selectedSize = size;
                    });
                  },
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 4),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    decoration: BoxDecoration(
                      color: selectedSize == size
                          ? CustomColor.primaryColor
                          : Colors.grey[200],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      children: [
                        Text(
                          '${size.toInt()}m',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: selectedSize == size
                                ? Colors.white
                                : Colors.black87,
                          ),
                        ),
                        Text(
                          _getSizeDescription(size),
                          style: TextStyle(
                            fontSize: 10,
                            color: selectedSize == size
                                ? Colors.white70
                                : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  String _getSizeDescription(double size) {
    if (size <= 50) return '小';
    if (size <= 100) return '中';
    if (size <= 200) return '大';
    if (size <= 500) return '超大';
    return '巨型';
  }

  void _savePixelArt() {
    if (drawingPoints.isEmpty) {
      Get.snackbar('提示', '请先绘制像素画');
      return;
    }

    // TODO: 将画布转换为图片，上传到服务器，然后返回数据
    Get.back(result: {
      'size': selectedSize,
      'drawingPoints': drawingPoints,
      // 实际使用时需要转换为图片并上传
    });
  }
}

/// 绘制点数据
class DrawingPoint {
  final Offset offset;
  final Paint paint;

  DrawingPoint(this.offset, this.paint);
}

/// 画布绘制器
class DrawingPainter extends CustomPainter {
  final List<DrawingPoint?> drawingPoints;

  DrawingPainter(this.drawingPoints);

  @override
  void paint(Canvas canvas, Size size) {
    for (int i = 0; i < drawingPoints.length - 1; i++) {
      if (drawingPoints[i] != null && drawingPoints[i + 1] != null) {
        canvas.drawLine(
          drawingPoints[i]!.offset,
          drawingPoints[i + 1]!.offset,
          drawingPoints[i]!.paint,
        );
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

